<template>
  <div class="my_page_container">
    <div class="bg-white">
      <q-table
        id="my-xls"
        bordered
        flat
        separator="cell"
        :tableTitle= "tableTitle"
        :columns="columns"
        row-key="name"
        :rows="dbFilterList"
        :pagination="dbPagination"
        :rows-per-page-options="[10,20]"
        selection="multiple"
        v-model:selected="selectedItems"
      >

        <!--  插槽：表格头部左侧    -->
        <template v-slot:top-left>
          <q-input outlined dense color="base" v-model="filterText" :input-style="{ width: '150px'}">
            <template v-slot:append>
              <q-icon name="search" color="indigo" />
            </template>
          </q-input>
        </template>

        <!--  插槽：表格头部左侧    -->
        <template v-slot:top-right>
          <div class="q-gutter-sm">
            <q-btn
              dense
              unelevated
              color="pink"
              label="导出"
              icon="mdi-database-export"
              @click="exportExcel"
            />
          </div>
        </template>

        <!--  插槽：某个单元格    -->
        <template #body-cell-connection="props">
          <q-td :props="props">
          {{devTbl[props.rowIndex].status ? '连接' : '未连接'}}
          </q-td>
        </template>

        <!--   底部插槽     -->
        <template v-slot:bottom>
          <AmyPagination :page-msg="dbPagination" @update="refreshTableAry"/>
        </template>
      </q-table>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, reactive, ref, watch, nextTick } from 'vue';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import BaseItem from '../../BaseItem.vue';
import api from 'axios';
import * as XLSX from 'xlsx';
import { socket }  from  'src/socket/websocket';
import { useScadaPacket } from 'src/hook/editor/useScadaPacket';
import { useCommonStore } from 'stores/commonStore';
import { storeToRefs } from 'pinia';
import useCommonVisitDatabase from 'src/hook/common/useCommonVisitDatabase';
import { ItemType } from 'src/hook/common/useCommonVisitType';
import { scaBaseUrlAPI } from 'src/util/ScaBaseConst';



export default defineComponent({
  name: 'ConnIndex',
  extends: BaseItem,
  components: {

  },
  setup (props, context) {
    //*********************************************************************************************
    //      store
    //*********************************************************************************************
    //数据库store
    const commonStore = useCommonStore();
    const {
      application,
      devTbl
    } = storeToRefs(commonStore);
    //*********************************************************************************************
    //      消息通知
    //*********************************************************************************************
    //消息通知
    const {
      showMessage
    } = useMessageNotify();

    //*********************************************************************************************
    //      读取表格数据
    //*********************************************************************************************
    //检索响应数据
    const state = reactive({
      itemData: {
        id: 0,
        typeId: 0,
        cname: '',
        commAddr: '',
        commPort: 0,
        admin: '',
        password: '',
        encryptionId: 0,
        protocolId: 0,
        projectId: 0,
        countryId: 0,
        provinceId: 0,
        sortCode: ''
      }
    });

    //查询数据库
    const fetchApi = () => {
      return api.post(scaBaseUrlAPI.SCA_DEVICE_API_PAGE, {
        projectId: application.value.projectId,
        pageNum: dbPagination.value.pageNum,
        pageSize: dbPagination.value.pageSize
      });
    };

    //删除记录
    const deleteApi = (item: ItemType) => {
      return api.post(scaBaseUrlAPI.SCA_DEVICE_API_DELETE, { id: item.id });
    };

    //增加记录
    const confirmAddApi = (item: ItemType) => {
      return api.post(scaBaseUrlAPI.SCA_DEVICE_API_ADD, {
        id: item.id,
        typeId: item.typeId,
        cname: item.cname,
        commAddr: item.commAddr,
        commPort: item.commPort,
        admin: item.admin,
        password: item.password,
        encryptionId: item.encryptionId,
        protocolId: item.protocolId,
        projectId: item.projectId,
        countryId: item.countryId,
        provinceId: item.provinceId,
        sortCode: item.sortCode,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    //修改记录
    const confirmEditApi = (item: ItemType) => {
      return api.post(scaBaseUrlAPI.SCA_DEVICE_API_UPDATE, {
        id: item.id,
        typeId: item.typeId,
        cname: item.cname,
        commAddr: item.commAddr,
        commPort: item.commPort,
        admin: item.admin,
        password: item.password,
        encryptionId: item.encryptionId,
        protocolId: item.protocolId,
        projectId: item.projectId,
        countryId: item.countryId,
        provinceId: item.provinceId,
        sortCode: item.sortCode,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    const {
      dbList,
      dbFilterList,
      dbPagination,
      filterList,
      loadList
    } = useCommonVisitDatabase(state.itemData, fetchApi, confirmAddApi, confirmEditApi, deleteApi);


    //*********************************************************************************************
    //      表格
    //*********************************************************************************************
    const columns = [
      {
        name: 'id',
        required: true,
        label: 'ID号',
        align: 'center',
        field: (row:any) => (row.id),
        sortable: true
      },
      { name: 'cname', align: 'center', label: '设备名称', field: 'cname' },
      { name: 'commAddr', align: 'center', label: 'IP地址', field: 'commAddr' },
      { name: 'commPort', align: 'center', label: '端口号', field: 'commPort' },
      { name: 'provinceId', align: 'center', label: '省份', field: 'provinceId' },
      { name: 'connection', align: 'center', label: '连接状态', field: 'connection' }
    ];

    //rows
    let tableTitle = ref('设备列表');
    let filterText = ref('');
    let selectedItems = ref([]);

    //检索显示
    const searchTableAry = () => {
      filterList(filterText.value);
    }

    //更新分页组件
    const refreshTableAry = (pageNum: number) => {
      dbPagination.value.pageNum = pageNum;
      loadList();
    }

    //导出excel
    const exportExcel = () => {
      let workbook = XLSX.utils.table_to_book(document.getElementById('my-xls')); //需要在table上定义一个id
      try {
        XLSX.writeFile(workbook, 'BOX信息.xlsx');
      } catch (e) {
        showMessage('导出失败,失败信息:!');
      }
    }

    //*********************************************************
    // 变量表
    //*********************************************************
    //socket通信函数
    const {
      wsRegisterDevice,
      wsReadDeviceConnection
    } = useScadaPacket();

    //*********************************************************************************************
    //      启动模块
    //*********************************************************************************************
    //监视检索框
    watch(filterText, () => {
      searchTableAry();
    });

    //监视dbFilterList
    watch(dbFilterList, () => {
      //清空
      commonStore.initDeviceTbl();

      //重新写入数据库
      dbFilterList.value.forEach((item) => {
        commonStore.addDeviceTbl(item.id, 0);
      });

      //重新注册设备
      if (socket) {
        //注册
        console.log('读取设备连接表');
        wsRegisterDevice(socket, devTbl.value);
        wsReadDeviceConnection(socket, devTbl.value);
      }
    }, { deep: true });


    //挂载组件
    onMounted(() => {
      //数据库初始化
      commonStore.initDeviceTbl();
      commonStore.initDevConnTbl();

      //加载数据
      loadList();
    });

    //卸载组件
    onUnmounted(() => {

    });

    return {
      columns,
      tableTitle,
      selectedItems,
      filterText,
      refreshTableAry,

      dbList,
      dbFilterList,
      dbPagination,

      exportExcel,

      devTbl
    }
  }
});
</script>

<style lang="scss" scoped>
.my_input {
  width: 150px;
}
</style>
